package org.ghost.http.testkit.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.ghost.http.testkit.dto.ResponseVO;
import org.ghost.http.testkit.entity.ConfigEnv;
import org.ghost.http.testkit.service.IConfigEnvService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2018-05-02
 */
@RestController
@RequestMapping("/configEnv")
public class ConfigEnvController extends BaseController {
    @Autowired
    private IConfigEnvService service;

    /**
     * 实体查询
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public ResponseVO search(@PathVariable Long id) {
        return getFromData(service.selectById(id));
    }

    /**
     * 实体删除
     */
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public ResponseVO del(@PathVariable Long id) {
        service.deleteById(id);
        return getSuccess();
    }

    /**
     * 实体添加
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseVO add(@RequestBody ConfigEnv entity) {
        service.insert(entity);
        return getSuccess();
    }


    /**
     * 实体修改
     */
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public ResponseVO update(@PathVariable Long id, @RequestBody ConfigEnv entity) {
        entity.setId(id);
        service.updateById(entity);
        return getSuccess();
    }

    /**
     * 分页查询
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseVO selectPage(Page<ConfigEnv> page) {
        page = page == null ? new Page<>(1, 10) : page;
        Wrapper<ConfigEnv> wrapper = null;
        if (MapUtils.isNotEmpty(page.getCondition())) {
            wrapper = new EntityWrapper<ConfigEnv>();
            for (Map.Entry<String, Object> item : page.getCondition().entrySet()) {
                if (StringUtils.isNotBlank(item.getKey()) && item.getValue() != null && StringUtils.isNotBlank(item.getValue().toString())) {
                    if (item.getValue() instanceof Long) {
                        wrapper.eq(item.getKey(), item.getValue().toString());
                    } else if (item.getValue() instanceof String) {
                        wrapper.like(item.getKey(), item.getValue().toString());
                    }
                }
            }
        }
        return getFromData(service.selectPage(page, wrapper));
    }
}
